#!/usr/bin/env python3
"""
注意力检测演示启动脚本

这个脚本会自动配置环境并启动注意力检测演示，
特别针对macOS系统进行了优化，抑制各种系统警告。

使用方法：
    python run_attention_demo.py

特性：
- 自动检测操作系统
- 配置macOS特定环境
- 抑制系统警告和错误消息
- 提供友好的用户界面
"""

import os
import sys
import platform
import subprocess
from pathlib import Path


def setup_environment():
    """设置运行环境"""
    print("🚀 正在启动儿童学习注意力检测演示")
    print("=" * 50)
    
    # 检测操作系统
    system = platform.system()
    print(f"操作系统: {system}")
    
    if system == 'Darwin':  # macOS
        print("🍎 检测到macOS系统，正在配置环境...")
        setup_macos_environment()
    elif system == 'Windows':
        print("🪟 检测到Windows系统")
    elif system == 'Linux':
        print("🐧 检测到Linux系统")
    
    print("✅ 环境配置完成")


def setup_macos_environment():
    """配置macOS环境"""
    # 设置环境变量以抑制各种警告
    env_vars = {
        'OPENCV_AVFOUNDATION_SKIP_AUTH': '1',
        'PYTHONWARNINGS': 'ignore',
        'NNPACK_DISABLE': '1',
        'PYTORCH_DISABLE_NNPACK_CHECK': '1',
        'QT_MAC_WANTS_LAYER': '1',
        'OPENCV_VIDEOIO_PRIORITY_MSMF': '0',
        'OPENCV_VIDEOIO_DEBUG': '0',
        'PYTHONHTTPSVERIFY': '0'
    }
    
    for key, value in env_vars.items():
        os.environ[key] = value
        print(f"  ✓ 设置 {key}={value}")


def check_dependencies():
    """检查依赖项"""
    print("\n🔍 检查依赖项...")
    
    required_packages = [
        'cv2',
        'numpy',
        'ultralytics',
        'PIL'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
            print(f"  ✓ {package}")
        except ImportError:
            print(f"  ✗ {package} (缺失)")
            missing_packages.append(package)
    
    if missing_packages:
        print(f"\n❌ 缺少依赖项: {', '.join(missing_packages)}")
        print("请运行以下命令安装:")
        if 'cv2' in missing_packages:
            print("  pip install opencv-python")
        if 'ultralytics' in missing_packages:
            print("  pip install ultralytics")
        if 'PIL' in missing_packages:
            print("  pip install Pillow")
        if 'numpy' in missing_packages:
            print("  pip install numpy")
        return False
    
    print("✅ 所有依赖项已安装")
    return True


def check_model_files():
    """检查模型文件"""
    print("\n📁 检查模型文件...")
    
    # 检查是否存在YOLO模型文件
    model_files = [
        'yolo11n-pose.pt',
        'yolo11n.pt',
        'yolov8n-pose.pt',
        'yolov8n.pt'
    ]
    
    found_model = False
    for model_file in model_files:
        if os.path.exists(model_file):
            print(f"  ✓ 找到模型文件: {model_file}")
            found_model = True
            break
    
    if not found_model:
        print("  ℹ️  未找到本地模型文件，将自动下载")
        print("  首次运行可能需要下载模型，请确保网络连接正常")
    
    return True


def run_demo():
    """运行演示程序"""
    print("\n🎬 启动注意力检测演示...")
    print("=" * 50)
    
    # 构建演示脚本路径
    demo_script = Path(__file__).parent / "examples" / "attention_detection_demo.py"
    
    if not demo_script.exists():
        print(f"❌ 找不到演示脚本: {demo_script}")
        return False
    
    try:
        # 使用当前Python解释器运行演示脚本
        cmd = [sys.executable, str(demo_script)]
        
        print(f"执行命令: {' '.join(cmd)}")
        print("\n控制说明:")
        print("  - 按 'q' 或 'Q' 或 ESC 键退出")
        print("  - 按 'r' 或 'R' 键重置历史数据")
        print("  - 关闭窗口也可以退出程序")
        print("\n" + "=" * 50)
        
        # 运行演示程序
        result = subprocess.run(cmd, cwd=Path(__file__).parent)
        
        if result.returncode == 0:
            print("\n✅ 演示程序正常退出")
        else:
            print(f"\n⚠️  演示程序退出，返回码: {result.returncode}")
        
        return True
        
    except KeyboardInterrupt:
        print("\n\n⏹️  用户中断程序")
        return True
    except Exception as e:
        print(f"\n❌ 运行演示程序时出错: {e}")
        return False


def main():
    """主函数"""
    try:
        # 设置环境
        setup_environment()
        
        # 检查依赖项
        if not check_dependencies():
            return 1
        
        # 检查模型文件
        check_model_files()
        
        # 运行演示
        if run_demo():
            print("\n🎉 感谢使用儿童学习注意力检测系统！")
            return 0
        else:
            return 1
            
    except KeyboardInterrupt:
        print("\n\n⏹️  程序被用户中断")
        return 0
    except Exception as e:
        print(f"\n💥 程序运行出错: {e}")
        import traceback
        traceback.print_exc()
        return 1


if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)
